import React, { useEffect, useState } from 'react';
import type { IRadioGroupOptionType } from '../../type';
import styles from './index.less';

interface IProps {
  /**
   * 值
   */
  value?: string;
  /**
   * 禁用
   */
  disabled?: true;
  /**
   * 改变事件
   */
  onChange?: (e: any) => void;
  /**
   * 选项
   */
  options: IRadioGroupOptionType[];
}

const RadioGroup = (props: IProps) => {
  const { options = [], value: _value, onChange, disabled = false } = props;
  const [value, setValue] = useState<any>();

  useEffect(() => {
    if (_value) {
      setValue(_value);
    } else {
      setValue(options[0].value);
    }
  }, [_value]);

  const onClick = (item: IRadioGroupOptionType) => {
    if (item.value !== value && !disabled) {
      setValue(item.value);
      onChange && onChange(item.value);
    }
  };

  return (
    <div className={styles.container}>
      {options.map((item) => {
        return (
          <div
            className={disabled ? styles.disItem : styles.item}
            style={{
              color: value === item.value ? item.color : item.defaultColor,
              backgroundColor:
                value === item.value ? item.backgroundColor : item.defaultBackgroundColor,
            }}
            key={item.value}
            onClick={() => onClick(item)}
          >
            {item.label}
          </div>
        );
      })}
    </div>
  );
};

export default RadioGroup;
